<template>
    <view class="create-menu">
        <view class="menu-title">
            <text>填写联系人信息</text>
        </view>
        <view style="height: calc(100% - 80rpx);">
            <scroll-view :style="{'height': (vuex_keyboardStatus ?  '100%' : 'calc(100% - 80rpx)')}" scroll-y="true">
                <view>
                    <view class="title">
                        基本信息
                    </view>
                    <u-form class="xh-form" :model="crmFormFields" :rules="crmRules" ref="crmForm" :errorType="['message']">
                        <u-form-item label-position="top" :prop="item.data.fieldName" :required="item.data.isNull == 1"
                            v-for="(item, index) in crmForm.crmFields" :key="index" :label="item.data.name">
                            <!-- 输入框组件 -->
                            <component is="XhInput" v-if="item.data.formType == 'text' || item.data.formType == 'number' || item.data.formType == 'floatnumber' || item.data.formType == 'mobile'  || item.data.formType == 'email'"
                                :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                                @value-change="fieldValueChange">
                            </component>
                            <!-- 单选组件 -->
                            <component is="XhSelect" v-if="item.data.formType == 'select'" :index="index" :item="item"
                                :value="item.value" :disabled="item.disabled" :relation="item.relation" @value-change="fieldValueChange">
                            </component>
                            <!-- 时间选择组件 -->
                            <component is="XhDateTime" v-if="item.data.formType == 'datetime' || item.data.formType == 'date'"
                                :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                                @value-change="fieldValueChange">
                            </component>
                            <!-- 关联表 -->
                            <component is="XhRelativeTable" v-if="item.data.formType == 'contacts' || item.data.formType == 'customer' || item.data.formType == 'contract' || item.data.formType == 'business'"
                                :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                                @value-change="fieldValueChange">
                            </component>
                            <!-- 新建关联数据 -->
                            <component is="XhCreate" v-if="item.data.formType == 'customer_contacts'" :index="index"
                                :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation"
                                @value-change="fieldValueChange">
                            </component>
                        </u-form-item>
                    </u-form>
                </view>

            </scroll-view>
        </view>
        <view class="xh-buttons" v-show="!vuex_keyboardStatus">
            <u-button class="xh-button-item" type="primary" @click="saveField()">保存</u-button>
        </view>
    </view>
</template>

<script>
    import {
        filedGetField,
        filedValidates
    } from "@/api/customer/common.js";
    import XhInput from '@/pages/customerManagement/common/components/CreateCom/XhInput';
    import XhSelect from '@/pages/customerManagement/common/components/CreateCom/XhSelect';
    import XhDateTime from '@/pages/customerManagement/common/components/CreateCom/XhDateTime';
    import XhRelativeTable from '@/pages/customerManagement/common/components/CreateCom/XhRelativeTable';
    import XhTextarea from '@/pages/customerManagement/common/components/CreateCom/XhTextarea';
    import crmTypeModel from '@/pages/customerManagement/model/crmTypeModel.js';
    import {
        crmContactsSave
    } from '@/api/customer/contacts';

    export default {
        props: {
            /** 值 */
            value: {
                type: [Array, String],
                default: () => {
                    return []
                }
            },
            /** 索引值 用于更新数据 */
            index: Number,
            /** 包含数据源 */
            item: Object,
            /**
             *  多选按钮
             */
            radio: {
                type: Boolean,
                default: false
            },
            disabled: {
                type: Boolean,
                default: false
            },
            /** 自定义数据源 */
            relation: Object,
        },
        data() {
            return {
                params: null,
                crmForm: {
                    crmFields: []
                },
                crmFormFields: {},
                crmRules: {},
                crmType: '',
            };
        },
        components: {
            XhInput,
            XhSelect,
            XhDateTime,
            XhRelativeTable
        },
        watch: {

        },
        computed: {

        },
        created() {
            this.getFields();
        },
        methods: {

            // 更改值
            fieldValueChange(data) {
                let item = this.crmForm.crmFields[data.index]
                item.value = data.value;
                //用于校验
                // this.crmFormFields[data.fieldName] = data.value;
                //用于校验
                if (data.value && data.value.length) {
                    if (item.data.isUnique == 1 || item.data.fieldType == 1) {
                        this.crmFormFields[data.fieldName] = data.value;
                    } else {
                        this.crmFormFields[data.fieldName] = "TRUE";
                    }
                } else {
                    this.crmFormFields[data.fieldName] = ''
                }
            },

            // 获取
            getFields() {
                let self = this;
                let params = {
                    label: crmTypeModel['contacts']
                }
                filedGetField(params).then(res => {
                    self.getCrmRulesAndModel(res.data)
                })
            },

            getCrmRulesAndModel(list) {
                let self = this;
                let fields = [];
                let formFields = {};
                let crmRules = {};
                for (let index = 0; index < list.length; index++) {
                    const item = list[index]
                    // 过滤字段
                    if (item.formType == 'customer') {
                        continue
                    }

                    /**
                     * 规则数据
                     */

                    crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item)
                    /**
                     * 表单数据
                     */
                    let params = {};
                    params['key'] = item.fieldName;
                    params['data'] = item;
                    params['disabled'] = item.isDisabled == 1;
                    params['value'] = item.value;
                    params['relation'] = {}; // 自定义参数
                    if (item.formType == 'datetime') {
                        // params['relation']['dateType'] = 'datetime-all';
                    } else if (item.formType == 'customer') {
                        //关联数据类型actionType
                        if (item.value.length) {
                            params['value'] = item.value;
                        } else {
                            params['value'] = []
                        }
                        params['relation']['actionType'] = 'customer';
                    }
                    fields.push(params);
                    //将表单中涉及的字段放到crmFormFields，用户后续form的校验
                    formFields[item.fieldName] = item.value;
                }
                this.crmForm.crmFields = fields;
                this.crmFormFields = formFields;
                this.crmRules = crmRules;
                self.$nextTick(function() {
                    self.$refs.crmForm.setRules(self.crmRules);
                })
            },

            getItemRulesArrayFromItem(item) {
                var tempList = []
                // 验证必填
                if (item.isNull == 1) {
                    tempList.push({
                        required: true,
                        message: item.name + '不能为空',
                        trigger: ['blur', 'change']
                    })
                }

                // 验证唯一
                if (item.isUnique == 1) {
                    var validateUnique = (rule, value, callback) => {
                        if (value.length == 0 || !value) {
                            callback()
                        } else {
                            var validatesParams = {}
                            validatesParams.fieldId = item.fieldId
                            validatesParams.value = value;
                            filedValidates(validatesParams)
                                .then(res => {
                                    callback()
                                })
                                .catch(error => {
                                    callback(new Error(error.msg ? error.msg : '验证出错'))
                                })
                        }
                    }
                    tempList.push({
                        validator: validateUnique,
                        trigger: item.formType == 'checkbox' || item.formType == 'select' ? ['change'] : [
                            'blur', 'change'
                        ]
                    })
                }

                if (item.formType == 'mobile') {
                    var validateCRMMobile = (rule, value, callback) => {
                        if (!value || value == '' || this.$u.test.mobile(value)) {
                            callback()
                        } else {
                            callback(new Error('手机格式有误'))
                        }
                    }
                    tempList.push({
                        validator: validateCRMMobile,
                        trigger: ['blur']
                    })
                } else if (item.formType == 'email') {
                    var validateCRMEmail = (rule, value, callback) => {
                        if (!value || value == '' || this.$u.test.email(value)) {
                            callback()
                        } else {
                            callback(new Error('邮箱格式有误'))
                        }
                    }
                    tempList.push({
                        validator: validateCRMEmail,
                        trigger: ['blur']
                    })
                }
                return tempList
            },

            // ==================== 保存数据 ===================
            // 保存草稿
            // saveDraftField() {
            //     this.saveField(false, true)
            // },
            // 保存数据
            saveField(saveAndCreate, isDraft = false) {
                // this.saveAndCreate = saveAndCreate
                let self = this;
                self.$refs.crmForm.validate(valid => {
                    if (valid) {
                        var params = self.getSubmiteParams(self.crmForm.crmFields)
                        self.submiteParams(params)
                    } else {
                        self.$u.toast("存在字段填写不规范！")
                        return false
                    }
                })
            },
            /** 提交数据 */
            submiteParams(params) {
                let self = this;
                if (this.relation.relativeType == 'customer') {
                    this.$emit('value-change', params);
                    this.$emit('close-table');
                }
                if (this.relation.relativeType == 'followRecord') {
                    crmContactsSave(params)
                        .then(res => {
                            self.$emit('value-change')
                        })
                        .catch(() => {
                            this.loading = false
                        })
                }

            },
            /** 获取上传url */
            getSubmiteRequest() {

            },
            /** 拼接上传传输 */
            getSubmiteParams(array) {
                var params = {
                    entity: {},
                    field: []
                }
                for (let index = 0; index < array.length; index++) {
                    const element = array[index]
                    if (element.data.fieldType == 1) {
                        params.entity[element.key] = this.getRealParams(element) || ''
                    } else {
                        element.data.value = this.getRealParams(element)
                        params.field.push(element.data)
                    }
                }
                if (this.relation.relativeType == 'followRecord') {
                    params.entity['customer_id'] = this.relation.customerId;
                }
                return params
            },

            // 关联客户 联系人等数据要特殊处理
            getRealParams(element) {
                return element.value
            },
        }
    };
</script>

<style scoped lang="scss">
    .title {
        width: 100%;
        background-color: #E9E8E8;
        border-left: 5px solid #18CC6C;
        padding: 5px 5px 5px 10px;
        box-sizing: border-box;
    }

    .xh-form {
        padding: 0 30rpx;
    }

    .xh-buttons {
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        display: flex;
        flex-direction: row;
        z-index: 10;

        .xh-button-item {
            width: 100%;
            border-radius: 0;
            border: none;
        }
    }

    .u-form-item {
        padding: 20rpx 0 0 0;
        line-height: 1;

        /deep/ .u-form-item__message {
            margin: 0;
            padding-bottom: 10rpx;
        }

        /deep/ .u-form-item--left {
            margin: 0 !important;
        }
    }

    .menu-title {
        text-align: center;
        height: 80rpx;
        font-size: 35rpx;
        line-height: 80rpx;
        border-bottom: 1px solid #efeff4;
    }
</style>
